package br.pucrs.lognplay.faces.bean;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;

import br.pucrs.lognplay.entity.User;
import br.pucrs.lognplay.service.UserManagementService;

@ManagedBean
@RequestScoped
public class LoginBean extends Bean {

	private String username;

	private String password;

	@EJB
	private UserManagementService userManagementService;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String login() {
		try {
			User user = userManagementService.getUserByUsername(username);

			if (user != null) {
				String userPassword = user.getPassword();

				if (userPassword.equals(password)) {
					loginUser(user);
					return "/protected/client/home.xhtml";
				}
			}

			addErrorMessage("Invalid username or password", null);
			return null;
		} catch (Exception e) {
			throw new BeanException("Unexpected error", e);
		}
	}
}
